<template>
  <view class="custom-tab-bar">
    <view 
      class="tab-item" 
      v-for="(item, index) in tabList" 
      :key="index"
      :class="{ active: currentIndex === index }"
      @click="switchTab(item.pagePath, index)"
    >
      <image 
        :src="currentIndex === index ? item.selectedIconPath : item.iconPath"
        class="tab-icon"
      />
      <view class="tab-text">{{ item.text }}</view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { onShow } from '@dcloudio/uni-app';

const tabList = ref([
  { 
    pagePath: "/pages/index/index", 
    text: "首页", 
    iconPath: "/static/icon/home.png",
    selectedIconPath: "/static/icon/home-active.png"
  },
  { 
    pagePath: "/pages/news-list/news-list", 
    text: "新闻", 
    iconPath: "/static/icon/news.png",
    selectedIconPath: "/static/icon/news-active.png"
  },
  { 
    pagePath: "/pages/weather/weather", 
    text: "天气", 
    iconPath: "/static/icon/weather.png",
    selectedIconPath: "/static/icon/weather-active.png"
  },
  { 
    pagePath: "/pages/video/video", 
    text: "视频", 
    iconPath: "/static/icon/video.png",
    selectedIconPath: "/static/icon/video-active.png"
  },
  { 
    pagePath: "/pages/topic/topic", 
    text: "话题", 
    iconPath: "/static/icon/topic.png",
    selectedIconPath: "/static/icon/topic-active.png"
  },
  { 
    pagePath: "/pages/user/user", 
    text: "未登录", 
    iconPath: "/static/icon/user.png",
    selectedIconPath: "/static/icon/user-active.png"
  }
]);

const currentIndex = ref(0);

// 页面显示时更新当前选中项
const updateCurrentTab = () => {
  const pages = getCurrentPages();
  if (pages.length === 0) return;
  
  const currentPageRoute = pages[pages.length - 1].route; // 当前页面路由（不带/）
  const activeIndex = tabList.value.findIndex(item => 
    item.pagePath.replace('/', '') === currentPageRoute // 统一格式匹配
  );
  
  if (activeIndex !== -1) {
    currentIndex.value = activeIndex;
  }
};

onMounted(updateCurrentTab);
onShow(updateCurrentTab); // 页面切换时重新计算

const switchTab = (path, index) => {
  currentIndex.value = index;
  uni.switchTab({ 
    url: path,
    fail: (err) => {
      console.error('TabBar跳转失败:', err);
      uni.showToast({ title: '跳转失败', icon: 'none' });
    }
  });
};
</script>

<style scoped>
.custom-tab-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 50px;
  background-color: #fff;
  border-top: 1px solid #eee;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  padding-bottom: env(safe-area-inset-bottom); /* 适配底部安全区 */
}
.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  flex: 1; /* 均分宽度 */
}
.tab-item.active {
  color: #007AFF;
}
.tab-item.active .tab-text {
  color: #007AFF;
}
.tab-icon {
  width: 24px;
  height: 24px;
  margin-bottom: 2px;
}
.tab-text {
  font-size: 11px;
}
</style>